import React, { useState, memo, useContext, useEffect, useRef } from 'react';
import { Input } from 'antd-mobile'
import ScanCode from '@/components/ScanCode';
import { MyContext } from '@/context/index';
import './index.less';

function Index({ getHandlePressVal, hideScan, searchIcon }) {
    const { placeholderTxt, inputVal } = useContext(MyContext)
    const [value, setValue] = useState('')
    const [visualScan, setVisualScan] = useState(false);
    const inputRef = useRef(null)
    const inputRef2 = useRef(null)
    useEffect(() => {
        setValue(inputVal)
        inputRef.current.focus()
    }, [inputVal])

    // const handlePress = () => {
    //     getHandlePressVal(value)
    // }
    const handleImageChange = (val) => {
        const file = val.target.files[0];
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e) => {
            console.log(e.target.result)
        }
    }

    // 二维码扫描
    const getResult = (txt) => {
        setVisualScan(false)
        if (txt == '返回') {
            getHandlePressVal('')
        } else {
            getHandlePressVal(txt)
        }
    }

    return (
        <div className='search-line'>
            <div className="search-input">
                <Input
                    ref={inputRef}
                    placeholder={placeholderTxt}
                    value={value}
                    onEnterPress={()=> getHandlePressVal(value)}
                    onChange={val => {
                        setValue(val)
                    }}
                />
                {
                    hideScan ? null :
                        <img onClick={() => setVisualScan(true)} className='s-img' src={require("../../assets/img/icon_scan.png").default} alt="" />
                }
                {
                    searchIcon ?
                        <img className='s-img' onClick={()=> getHandlePressVal(value)} style={{ left: 50 }} src={require("../../assets/img/icon_search.png").default} alt="" /> : null
                }
            </div>

            <input style={{ display: 'none' }}
                ref={inputRef2}
                type="file"
                accept="image/*"
                onChange={handleImageChange}
            />

            {
                visualScan ? <ScanCode getResult={getResult}></ScanCode> : null
            }
        </div>
    );
}

export default memo(Index);
